package tech.edwardvan.springsecuritydemo.security.handler;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import tech.edwardvan.springsecuritydemo.common.ResponseCode;
import tech.edwardvan.springsecuritydemo.common.ServerResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT权限不足处理程序
 * 用户未通过认证访问受保护的资源
 *
 * @author EdwardVan
 */
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServerResponse serverResponse = new ServerResponse(ResponseCode.FORBIDDEN.getCode(), "无权限访问,请先登录!", authException != null ? authException.getMessage() : null);
        IoUtil.writeUtf8(response.getOutputStream(), true, JSONUtil.toJsonStr(serverResponse));
    }
}
